package com.example.wechat;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.wechat.utils.SecurityUtils;
import com.example.wechat.utils.UserManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class LoginActivity extends AppCompatActivity {
    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private TextView tvForgotPassword;
    private Button btnWeChatLogin;
    private Button btnQQLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 检查是否已登录
        if (UserManager.getInstance(this).isLoggedIn()) {
            startMainActivity();
            return;
        }
        
        setContentView(R.layout.activity_login);
        initViews();
        setupListeners();
    }

    private void initViews() {
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegister = findViewById(R.id.tvRegister);
        tvForgotPassword = findViewById(R.id.tvForgotPassword);
        btnWeChatLogin = findViewById(R.id.btnWeChatLogin);
        btnQQLogin = findViewById(R.id.btnQQLogin);
    }

    private void setupListeners() {
        btnLogin.setOnClickListener(v -> attemptLogin());
        tvRegister.setOnClickListener(v -> startRegisterActivity());
        tvForgotPassword.setOnClickListener(v -> startForgotPasswordActivity());
        btnWeChatLogin.setOnClickListener(v -> handleWeChatLogin());
        btnQQLogin.setOnClickListener(v -> handleQQLogin());
    }

    private void attemptLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // 在后台线程中验证登录
        new Thread(() -> {
            boolean loginSuccess = verifyLogin(username, password);
            runOnUiThread(() -> {
                if (loginSuccess) {
                    startMainActivity();
                } else {
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
            });
        }).start();
    }

    private boolean verifyLogin(String username, String password) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = MySQLConnection.getConnection();
            if (conn == null) {
                return false;
            }
            
            String sql = "SELECT * FROM users WHERE username = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            rs = stmt.executeQuery();
            
            if (rs.next()) {

                String storedHash = rs.getString("password");
                if (password.equals(storedHash)) {
                    // 生成新的token并保存用户信息
                    String userId = rs.getString("user_id");
                    String token = SecurityUtils.generateToken(userId);
                    String phone = rs.getString("phone");
                    String email = rs.getString("email");
                    String avatar = rs.getString("avatar_url");
                    
                    UserManager.getInstance(this).saveUserInfo(
                        userId, username, token, phone, email, avatar
                    );
                    return true;
                }
            }
            return false;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    private void startRegisterActivity() {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

    private void startForgotPasswordActivity() {
        Intent intent = new Intent(this, ForgotPasswordActivity.class);
        startActivity(intent);
    }

    private void handleWeChatLogin() {
        // TODO: 实现微信登录
        Toast.makeText(this, "微信登录功能开发中", Toast.LENGTH_SHORT).show();
    }

    private void handleQQLogin() {
        // TODO: 实现QQ登录
        Toast.makeText(this, "QQ登录功能开发中", Toast.LENGTH_SHORT).show();
    }
} 